<script setup lang="ts">
import { getCurrentInstance, ref, reactive, watch, onBeforeMount, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { Autoplay } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import 'swiper/css/autoplay'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
import Masonry from 'masonry-layout'
const { proxy } = getCurrentInstance()

/* ---- */
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* ---- */
const user = reactive({
  cateRootId: 0,
  // ----
  title: '',
  // ----
  share_title: proxy.$shareTitle,
  share_desc: proxy.$shareDesc,
  share_icon: proxy.$shareIcon
})
// ----
const infoSch = ref(null)
const forSearch = ref(proxy.$Store.get('forSearch') || {})
// ----
let cates = []
let units = []
// ----
const forAdvs = ref([])
const forFreeAdvs = 3 / 1
const setTrueStyleAdvs = ref({})
const forAutoplay = {
  delay: 5000,
  disableOnInteraction: false
}
const modules = [Autoplay]
// --瀑布流布局参数--
let trueWidth = 0
const rowCount = 2
let masonry = null
// --mescroll--
let noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const sliding = ref()
const layer = ref()
const layerBox = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// --设置微信分享--
const setWebShare = (info) => {
  const forSn = proxy.$Store.get('SN')
  const currentUrl = window.location.href.split('#')[0]
  const shareLink = (Number(currentUrl.indexOf('sn=')) === Number(-1)) ? ((Number(currentUrl.indexOf('?')) === Number(-1)) ? currentUrl + '?sn=' + forSn : currentUrl + '&sn=' + forSn) : currentUrl
  proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
    if (!obj) return
    // ----
    obj.hideMenuItem()
    obj.showMenuList(['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:favorite', 'menuItem:share:QZone'])
    // ----
    obj.share({
      title: info.title,
      desc: info.desc,
      link: shareLink,
      imgUrl: info.imgUrl
    })
  })
}
// ----
const getTrueStyleAdvs = () => {
  if (proxy.$refs.forTrueWidthAdvs) {
    const imgEL = proxy.$refs.forTrueWidthAdvs
    const imgRatio = forFreeAdvs
    setTrueStyleAdvs.value = { height: `${Math.round(imgEL.offsetWidth / imgRatio)}px` }
  }
}
// --商品瀑布流布局--
const setListPos = () => {
  if (proxy.$refs.dataList) {
    const waterBox = proxy.$refs.dataList
    const waterItemWidth = Number(waterBox.offsetWidth / rowCount)
    masonry = new Masonry(waterBox, {
      columnWidth: waterItemWidth,
      itemSelector: '.water_item'
    })
  }
}
// ----
const getCurrencyInfo = async (callback) => {
  // --获取用户信息 & 顶部广告 & 商品分类 & 自定义计量单位 & 云仓计量单位 --
  const forUserData = { params: { 'DealerSearch[id]': proxy.$route.query.dealer_id } }
  const forImgData = {
    params: {
      'AdsSearch[type]': 4,
      'AdsSearch[dealer_id]': proxy.$route.query.dealer_id,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  const forCateData = {
    params: {
      'ProCategorySearch[dealer_id]': proxy.$route.query.dealer_id,
      'ProCategorySearch[parent_id]': 0,
      // --是否云仓分类--
      'ProCategorySearch[is_store]': 0,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  const forUnitData = {
    params: {
      'MeasuringUnitSearch[dealer_id]': proxy.$route.query.dealer_id,
      // --是否云仓计量单位--
      'MeasuringUnitSearch[is_store]': 0,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('dealer/index', forUserData),
    proxy.$Axios.get('ads/index', forImgData),
    proxy.$Axios.get('pro-category/index', forCateData),
    proxy.$Axios.get('measuring-unit/index', forUnitData)
  ]).then(proxy.$Axios.spread((userData, imgData, cateData, unitData) => {
    // --用户信息--
    const UData = userData.items[0] || {}
    proxy.$Myfun.getJsonData(UData.ads_content, (resJson) => {
      if (resJson[0].name) user.title = proxy.$Myfun.setText(resJson[0].name)
    })
    if (UData.name) user.share_title = proxy.$Myfun.setText(UData.name)
    if (UData.remark) user.share_desc = proxy.$Myfun.setText(UData.remark)
    proxy.$Myfun.getJsonData(UData.avatar, (resJson) => {
      if (Number(resJson.length) > 0) user.share_icon = resJson[0].image
    })
    // --顶部广告--
    const advItems = []
    imgData.items.forEach((item) => {
      let forAdv = {}
      proxy.$Myfun.getJsonData(item.img_json, (resJson) => {
        forAdv = {
          image: resJson[0].image,
          goods_id: resJson[0].goods_id
        }
      })
      advItems.push(forAdv)
    })
    forAdvs.value = advItems
    // --商品分类--
    const cateItems = []
    cateData.items.forEach((item, index) => {
      let forIcon = ''
      proxy.$Myfun.getJsonData(item.icon_json, (resJson) => { forIcon = resJson[0].image })
      cateItems.push({
        value: String(item.id),
        text: item.name,
        icon: forIcon
      })
    })
    cates = cateItems
    // --计量单位--
    const unitItems = []
    unitData.items.forEach((item, index) => {
      unitItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    units = unitItems
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // --设置网页title--
  const forTitle = user.title
  setAppTitle(forTitle)
  // --设置微信分享信息--
  const forShare = {
    title: user.share_title,
    desc: user.share_desc,
    imgUrl: user.share_icon
  }
  setWebShare(forShare)
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'proc/index',
    forData: {
      params: {
        'ProductSearch[name]': infoSch.value,
        // ----
        'ProductSearch[dealer_id]': proxy.$route.query.dealer_id,
        // --是否展示商品--
        'ProductSearch[is_show]': 0,
        // --是否云仓商品--
        'ProductSearch[is_store]': 0,
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
      // ----
      if (Number(items.value.length) > 0) nextTick(() => { setListPos() })
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forAdv = ''
    let forStyle = {}
    await proxy.$Myfun.getJsonData(item.img_top, (resJson) => {
      forAdv = resJson[0].image
      // ----
      const imgRatio = Number(resJson[0].width / resJson[0].height)
      forStyle = { height: `${Math.round(trueWidth / imgRatio)}px` }
    })
    // ---
    let psize = [{
      name: '',
      price: '',
      unit: 0
    }]
    await proxy.$Myfun.getJsonData(item.price_json, (resJson) => { psize = resJson })
    // ----
    let forUnit = ''
    units.some((current) => {
      if (String(current.value) === String(psize[0].unit)) forUnit = current.text
    })
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      image: forAdv,
      imgStyle: forStyle,
      price: Number(psize[0].price).toFixed(2),
      unitTxt: forUnit,
      noteTxt: proxy.$Myfun.setText(item.proremark_id)
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
  // ----
  getAuditFun(3)
}
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      if (Number(item.goods_id) > 0) proxy.$Myfun.openPage(proxy, 'push', 'GoodsView', { dealer_id: proxy.$route.query.dealer_id, goods_id: item.goods_id })
      break
    }
    case 2: {
      const options = {
        type: 0,
        forall: { show: true, text: '不限分类' },
        slideName: 'slideLeft',
        boxClass: 'SLB-box-left',
        title: '选择分类',
        list: cates,
        callback: (info) => {
          user.cateRootId = info[1]
          proxy.$Myfun.openPage(proxy, 'push', 'GoodsListCate', { dealer_id: proxy.$route.query.dealer_id })
        }
      }
      proxy.$Myfun.isIndepth(sliding.value, 'open', options)
      break
    }
    case 3: {
      const newItems = []
      newItems.push(infoSch.value)
      proxy.$Myfun.setSearchRes(proxy, newItems, ['infoSch'], (result) => { forSearch.value = result })
      break
    }
    case 4: {
      proxy.$Myfun.openPage(proxy, 'push', 'GoodsView', { dealer_id: proxy.$route.query.dealer_id, goods_id: item.id })
      break
    }
  }
}

/* ---- */
watch(() => forSearch.value, (newVal, oldVal) => {
  infoSch.value = newVal.infoSch
  // --重新请求数据--
  mescroll.scrollTo(0)
  mescroll.resetUpScroll()
}, { deep: true })

/* ---- */
onBeforeMount(() => {
  infoSch.value = forSearch.value.infoSch
})
onMounted(() => {
  setTimeout(() => { getTrueStyleAdvs() }, 100)
  // ----
  getCurrencyInfo(() => {
    setTimeout(() => { if (proxy.$refs.forTrueWidth) trueWidth = proxy.$refs.forTrueWidth.offsetWidth }, 100)
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => {
  if (mescroll) mescroll.destroy()
  proxy.$Store.remove('forSearch', () => {
    if (Number(user.cateRootId) > 0) proxy.$Myfun.setSearchRes(proxy, [user.cateRootId], ['tag'])
  })
})
</script>

<template>
  <div>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <div class="list-li-adv"><div ref="forTrueWidthAdvs"></div></div>
        <div class="shop-adv" :style="setTrueStyleAdvs" v-if="Number(forAdvs.length) > 0">
          <swiper :modules="modules" :autoplay="forAutoplay">
            <swiper-slide class="xw-act" v-for="(item, index) in forAdvs" @click="getAuditFun(1, item)"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.image + ')' }"></div></swiper-slide>
          </swiper>
        </div>
        <!---->
        <div class="forTop xw-sticky xw-bg-gray xw-flex xw-flex-align">
          <a class="far fa-grid-2 TOP-icon TOP-L xw-color-12 xw-flex xw-flex-center" @click="getAuditFun(2)"></a>
          <div class="TOP-sch xw-bg-white xw-radius-3 xw-flex-W1 xw-flex xw-flex-align">
            <em class="TOP-L far fa-search"></em>
            <p class="xw-flex-W1"><input class="schText" type="text" placeholder="输入关键词找商品" v-model.trim="infoSch"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="infoSch"></em></transition>
            <span class="TOP-btn TOP-R xw-Lfg" @click="getAuditFun(3)">搜索</span>
          </div>
        </div>
        <!---->
        <ul class="list-goods water_box" ref="dataList">
          <li class="water_item" :class="'water_item_' + rowCount" v-for="(item, index) in items"><a class="xw-radius-3 xw-bg-white" @click="getAuditFun(4, item)">
            <div class="LGD-img" :style="item.imgStyle"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.image + ')' }"></div></div>
            <div class="LGD-con">
              <div class="LGD-title xw-ellipsis-2">{{item.name}}</div>
              <div class="LGD-price xw-flex xw-flex-align">
                <span class="xw-color-11">￥</span>
                <div class="xw-color-11">{{item.price}}</div>
                <span v-if="item.unitTxt">/{{item.unitTxt}}</span>
              </div>
              <div class="LGD-note xw-color-19  xw-ellipsis">{{item.noteTxt}}</div>
            </div>
          </a></li>
          <div class="list-li" :class="'water_item_' + rowCount"><div ref="forTrueWidth"></div></div>
        </ul>
      </div>
    </div>
    <sliding-view ref="sliding"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
  </div>
</template>

<style scoped>
/* ---- */
.shop-adv .swiper { height: 100%; }

/* ---- */
.list-goods { margin: 0 0.5rem; position: relative; }
.list-goods li { padding: 0 0 1rem; }
.list-goods li a { margin: 0 0.5rem; display: block; overflow: hidden; }
.LGD-con { padding: 0 0 1rem; }
.LGD-title { margin: 1rem 1rem 0; min-height: 5rem; line-height: 2.5rem; font-size: 1.6rem; text-align: justify; word-break: break-all; word-wrap: break-word; }
.LGD-price { margin: 0.5rem 1rem 0; }
.LGD-price div { font-size: 2rem; }
.LGD-note { margin: 0.5rem 1rem 0; min-height: 2rem; line-height: 2rem; text-align: justify; word-break: break-all; word-wrap: break-word; }
.list-li div { margin: 0 0.5rem; height: 0; }

/* --forWater-- */
.water_item { position: absolute; transition: all 0.3s ease-in-out; }
.water_item_2 { width: 50%; }
.water_item_3 { width: 33.3333%; }
.water_item_4 { width: 25%; }
</style>
